package configs

import (
	"gopkg.in/yaml.v3"
	"io/ioutil"
	"time"
)

type DHCPConfig struct {
	Enabled       bool   `yaml:"enabled"` // 是否启用 DHCP 服务
	Interface     string `yaml:"interface"`
	ServerIP      string `yaml:"serverIP"`
	Port          int    `yaml:"port"`
	Subnet        string `yaml:"subnet"`
	Gateway       string `yaml:"gateway"`
	DNS           string `yaml:"dns"`
	StartIP       string `yaml:"startIP"`
	LeaseRange    int    `yaml:"leaseRange"`
	LeaseDuration int    `yaml:"leaseDuration"`
	LeaseFile     string `yaml:"lease_file"` // DHCP租约文件路径
}

type Config struct {
	Logging struct {
		OutputType    string `yaml:"output_type"`
		OutputPath    string `yaml:"output_path"`
		MaxSizeMB     int    `yaml:"max_size_mb"`
		MaxBackups    int    `yaml:"max_backups"`     // 最大备份数量
		MaxAgeDays    int    `yaml:"max_age_days"`    // 最大保留天数
		Compress      bool   `yaml:"compress"`        // 是否压缩
		Level         string `yaml:"level"`           // 日志级别
		EnableFileLog bool   `yaml:"enable_file_log"` // 是否启用文件日志
	} `yaml:"logging"`
	DNS struct {
		Port            int           `yaml:"port"`
		ServerConf      string        `yaml:"server_conf"`
		RecursiveDNS    string        `yaml:"recursive_dns"`
		Whitelist       string        `yaml:"whitelist"`
		CacheTimeoutStr string        `yaml:"cache_timeout"`
		CacheTimeout    time.Duration // Add cache timeout configuration
	} `yaml:"dns"`
	HTTPS struct {
		Port       int    `yaml:"port"`
		ServerPath string `yaml:"server_path"`
	} `yaml:"https"`
	DHCP DHCPConfig `yaml:"dhcp"`
}

var AppConfigInstance *Config

func LoadConfig(path string) (*Config, error) {
	file, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, err
	}

	config := &Config{}
	err = yaml.Unmarshal(file, config)
	if err != nil {
		return nil, err
	}

	//转化CacheTimeOut
	if config.DNS.CacheTimeoutStr != "" {
		duration, err := time.ParseDuration(config.DNS.CacheTimeoutStr)
		if err != nil {
			return config, err
		}
		config.DNS.CacheTimeout = duration
	}

	AppConfigInstance = config
	return config, nil
}
